package com.phone.client.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: myclms
 * @description: 用于身份证信息提取
 * @author: 大鱼
 * @create: 2021-08-04 11:58
 **/
public  class OrcScanUtil {
    static String host = "http://dm-51.data.aliyun.com";
    static String path = "/rest/160601/ocr/ocr_idcard.json";
    static String appcode = "a96f590e09434b82a00e89c08b553417";
    static String method = "POST";

    public static  Map IdInfo(String imgurl,String side) {
     //   身份证正反面类型:face/back
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");

        Map<String, String> querys = new HashMap<String, String>();
        // 对图像进行base64编码
        String imgBase64 = imgurl;

        //configure配置
        JSONObject configObj = new JSONObject();
        configObj.put("side", side);

        String config_str = configObj.toString();

        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        if (configObj.size() > 0) {
            requestObj.put("configure", config_str);
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                System.out.println("Http code: " + stat);
                System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                String res = EntityUtils.toString(response.getEntity());
                HashMap res_obj = JSON.parseObject(res,HashMap.class);
                return res_obj;
            }
            String res = EntityUtils.toString(response.getEntity());
            HashMap res_obj = JSON.parseObject(res,HashMap.class);
            return res_obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}



